package com.demo.controller;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.demo.common.model.R;
import com.demo.common.model.SecurityUser;
import com.demo.common.utils.AuthUtils;
import com.demo.entity.User;
import com.demo.service.UserService;
import com.demo.vo.UserDetailVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 用户管理模块
 */
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    public PasswordEncoder passwordEncoder;

    /**
     * 获取登录认证用户信息
     * @return
     */
    @GetMapping("/login/info")
    public R<SecurityUser> loadLoginUserInfo(){
        return R.OK(AuthUtils.getLoginSecurityUser());
    }

    /**
     * 获取登录用户详细详细
     * @return
     */
    @GetMapping("/derail/info")
    public R<UserDetailVo> loadUserDetailInfo(){
        UserDetailVo userDetailVo = userService.queryUserDetailInfoByUserId(AuthUtils.getLoginUserId());
        return R.OK(userDetailVo);
    }
    /**
     * 验证旧密码
     */
    @GetMapping("/checkOld")
    public R<Boolean> checkOldPwd(@RequestParam String oldPwd){
       return R.OK(passwordEncoder.matches(oldPwd,AuthUtils.getLoginSecurityUser().getPassword()));
    }
    /**
     * 修改用户更改密码
     */
    @PutMapping("/modifyPwd")
    public R<String> modifyUserPwd(@RequestBody User user){
        user.setId(AuthUtils.getLoginUserId()); // 被修改 id
        user.setLoginPwd(passwordEncoder.encode(user.getLoginPwd())); // 加密完进行修改
        user.setEditBy(AuthUtils.getLoginUserId()); // 编辑人
        user.setEditTime(new Date()); // 编辑时间
        return userService.updateById(user) ? R.OK(null) : R.FAIL("修改密码失败");
    }

    /**
     * 判断用户是否登录
     */
    @GetMapping("/isLogin")
    public R<String> isLogin(){
        return R.OK(null);
    }

    /**
     * 分页查询用户列表（使用pageHelper分页插件）
     */
    @GetMapping("/helper/page")
    public R<PageInfo<User>> loadUserHelperPage(@RequestParam Integer current,
                                                @RequestParam(required = false,defaultValue = "10") Integer pageSize){
        PageInfo<User> page = userService.queryUserHelperPage(current,pageSize);
        return R.OK(page);
    }
    /**
     * 根据用户标识查询详细信息
     */
    @GetMapping("/detail/info/{userId}")
    public R<UserDetailVo> loadUserDetailInfoById(@PathVariable("userId") Integer userId){
        UserDetailVo userDetailVo = userService.queryUserDetailInfoByUserId(userId);
        return R.OK(userDetailVo);
    }
    /**
     * 新增用户
     */
    @PostMapping
    public R<String> saveUser(@RequestBody User user){
        user.setCreateTime(new Date());
        user.setCreateBy(AuthUtils.getLoginUserId());
        user.setLoginPwd(passwordEncoder.encode(user.getLoginPwd()));
        boolean save = userService.save(user);
        return save ? R.OK(null) :R.FAIL("保存用户失败");
    }
    /**
     * 根据用户标识查询用户信息
     */
    @GetMapping("/info/{userId}")
    public R<User> loadUserInfo(@PathVariable("userId") Integer userId){
        User user = userService.getById(userId);
        return R.OK(user);
    }
    /**
     * 修改用户信息
     */
    @PutMapping
    public R<String> modifyUser(@RequestBody User user){
        user.setEditBy(AuthUtils.getLoginUserId());
        user.setEditTime(new Date());
        boolean flag = userService.updateById(user);
        return flag ? R.OK(null) : R.FAIL("修改失败!");
    }
    /**
     * 删除用户
     */
    @DeleteMapping("/{userId}")
    public R<String> delUser(@PathVariable("userId") Integer userId){
        boolean result = userService.removeById(userId);
        return result ? R.OK(null) : R.FAIL("删除失败");
    }
    /**
     * 批量删除
     */
    @DeleteMapping("/batch/{userIds}")
    public R<String>removeUserList(@PathVariable List<Integer> userIds){
        boolean removed = false;
        System.out.println(userIds);
        try {

            removed = userService.removeByIds(userIds);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return removed ? R.OK(null) : R.FAIL("批量删除失败");
    }
    /**
     * 查询所有用户列表
     *
     */
    @GetMapping("/list")
    public R<List<User>> loadUserList(){
        List<User> list = userService.list(new LambdaQueryWrapper<User>().orderByDesc(User::getCreateTime));
        return R.OK(list);
    }
}
